package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
	jwt "github.com/golang-jwt/jwt/v5"
)

var (
	// ErrTokenExpired token过期
	ErrTokenExpired = errors.New("token is expired")
	// ErrTokenInvalid token无效
	ErrTokenInvalid = errors.New("token is invalid")
)

func ParseTokenToMap(tokenString, secret string) (map[string]interface{}, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		// 检查是否是因为token过期导致的错误
		if errors.Is(err, jwt.ErrTokenExpired) {
			// 即使过期，我们仍然可以尝试获取claims
			if claims, ok := token.Claims.(jwt.MapClaims); ok {
				return claims, ErrTokenExpired
			}
		}
		return nil, ErrTokenInvalid
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		return claims, nil
	}
	return nil, ErrTokenInvalid
}
func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	if len(crypted)%blockSize != 0 {
		return nil, errors.New("common.AesDecrypt: input not full blocks")
	}

	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = pkcs7UnPadding(origData)
	return origData, nil
}
func pkcs7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
func DecryptData(data string) ([]byte, error) {
	aseKey := "MmyfEFDl534tqwlLSWPQGKe0JqOBBtoy"
	base64Decode, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return nil, err
	}
	return AesDecrypt(base64Decode, []byte(aseKey))
}
